The System.IO namespace provides a class named DriveInfo. Like Directory.GetLogicalDrives(), the static DriveInfo.GetDrives() method allows you to discover the names of a machine’s drives. Unlike Directory.GetLogicalDrives(), however, DriveInfo provides numerous other details (e.g., the drive type, available free space, and volume label). Consider the following Program class defined within a new Console Application named DriveInfoApp (don’t forget to import System.IO):
class Program { static void Main(string[] args) { Console.WriteLine("***** Fun with DriveInfo *****\n"); // Get info regarding all drives. DriveInfo[] myDrives = DriveInfo.GetDrives(); // Now print drive stats. foreach(DriveInfo d in myDrives) { Console.WriteLine("Name: {0}", d.Name); Console.WriteLine("Type: {0}", d.DriveType); // Check to see whether the drive is mounted. if(d.IsReady) { Console.WriteLine("Free space: {0}", d.TotalFreeSpace); Console.WriteLine("Format: {0}", d.DriveFormat); Console.WriteLine("Label: {0}", d.VolumeLabel); Console.WriteLine(); } } Console.ReadLine(); } }
Here is some possible output:
***** Fun with DriveInfo ***** Name: C:\ Type: Fixed Free space: 587376394240 Format: NTFS Label: Mongo Drive Name: D:\ Type: CDRom Name: E:\ Type: CDRom Name: F:\ Type: CDRom Name: H:\ Type: Fixed Free space: 477467508736 Format: FAT32 Label: My Passport
At this point, you have investigated some core behaviors of the Directory, DirectoryInfo, and DriveInfo classes. Next, you’ll learn how to create, open, close, and destroy the files that populate a given directory.
Source Code You can find the DriveInfoApp project under the Chapter 20 subdirectory.